﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Helpers;
using System.Web.Script.Serialization;

namespace Free2AskWeb.Controllers
{
    [Authorize(Roles="admin")]
    public class TagController : Controller
    {
        //
        // GET: /Tag/
        private Free2AskModel.Free2AskDBEntities db;
        public TagController()
        {
            db = new Free2AskModel.Free2AskDBEntities();
        }

        public ActionResult Index()
        {
            var tags = from t in db.Tags
                       //orderby t.Frequency descending,t.Name 
                       select t;
                     
            return View(tags.ToList().OrderByDescending(t=>t.Frequency).ThenBy(t=>t.Name));
        }

        public ActionResult Delete(string tagName)
        {
            db.Tags.Where(t => t.Name.Trim().ToLower() == tagName.Trim().ToLower()).ToList().ForEach(t => {
                if(t.Frequency>0)
                {
                    var posts = t.Posts.ToList();
                    foreach (var p in posts)
                    {
                        t.Posts.Remove(p);
                        //p.Tags.Remove(t);
                    }
                }
                db.DeleteObject(t);                
            });
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        [HttpPost]
        public JsonResult GetTags(string keyword)
        {
            keyword=keyword.Trim();

            var tags = from t in db.Tags                        
                       select new { TagName = t.Name, Description = t.Description };
            if (keyword != null)
            {
                tags=tags.Where(t=>t.TagName.Contains(keyword));
            }

            JavaScriptSerializer jss = new JavaScriptSerializer();
            return Json(jss.Serialize(tags.ToList()));
            //return Json(tags);

            //return Json(new string[]{"T1","T2","T3"});
        }

    }
}
